#用户管理 add by Luxh

sys_user = require('../models/sys_user')
SysUser = sys_user.SysUser
common_util = require('../services/common_util')
dataPage = require('../services/dataPage').queryPage
SysRole = require('../models/sys_role').SysRole
resErr = require('./util').resErr
ObjectId = require('mongoose').Types.ObjectId


express = require('express')
app = express()


#用户列表
exports.user_list = (req,res) ->
  params = {}
  #相当于sql里面like的写法
  params.username = {'$regex': req.param("username")}  unless !req.param("username")
  params.real_name = {'$regex': req.param("real_name")}  unless !req.param("real_name")
  sorts = {_id:-1}
  dataPage SysUser,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)

#查看用户的角色信息
exports.user_role_list = (req,res) ->
  user_id = req.param("user_id")
  if !user_id
    res.json({'success':false,'err_msg':'编码不得为空！'})
  else
    SysUser.findById user_id,(err,user) ->
      if err
        resErr(res,err)
      else
        role_array = user.roles
        params = {}
        params._id = {'$in':role_array}
        sorts = {_id:-1}
        dataPage SysRole,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
          if err
            resErr(res,err)
          else
            res.json(results)


#获取重定向信息
exports.user_get_redirect_info = (req,res) ->
  # redirect_protocol = config_admin.admin_redirect.redirect_protocol
  # redirect_host = config_admin.admin_redirect.redirect_host
  redirect_protocol = req.redirect_protocol
  redirect_host = req.hostname
  res.json({"redirect_host":redirect_host,"redirect_protocol":redirect_protocol});

#获取登录url
exports.user_get_login_url = (req,res) ->
  login_uri = oauth2_admin.getAuthorizeUrl(0, req)
  res.json({"login_uri":login_uri});


#退出
exports.user_logout = (req,res) ->
  if req.session?.user
    req.session.user = null
  if req.session?.admin
    req.session.admin = null
  req.session?.destroy()
  res.clearCookie(config.oauth2.cookie_name,{ path:'/',domain:'.gf.com.cn' })
  res.json({"flag":"success"})

#给用户赋予资讯栏目权限
exports.user_auth_category = (req, res) ->
  console.log req.session.admin_user
  console.log req.session.admin
  console.log req.session.user
  category_ids = req.param('categorys') #栏目编码
  user_id = req.param('user_id')  #_id
  #resErr res, '栏目id不能为空！' if !category_ids
  resErr res, '用户id不能为空！' if !user_id
  category_id_ary = []
  if category_ids
    category_id_ary = category_ids.split ',' 
  params = {}
  params.categorys = category_id_ary
  SysUser.update {_id: ObjectId(user_id)},params,(err) ->
    return resErr res, err if err
    res.json({flag: 'success'})





